from fastapi import APIRouter
from fastapi.params import Depends
from fastapi import Query
from tortoise.transactions import in_transaction
from tortoise.contrib.pydantic import pydantic_model_creator
from tortoise import connections
from datetime import datetime, timedelta
import uuid
from decimal import Decimal

from MyOAuth import my_oauth2_scheme
from db.models.sale import Sale, SaleItem
from db.models.product import Product
from db.models.customer import Customer
from db.models.warehouse import Warehouse
from db.models.store import Store
from db.models.user import User
from ApiResponse import ApiResponse, PageResult
from pydantic import BaseModel, Field
from typing import List, Optional

# 创建路由
sale_router = APIRouter()


class SaleItemRequest(BaseModel):
    """销售订单商品项请求模型"""
    pid: int = Field(example=1, description='商品ID')
    saletype: str = Field(example='常规销售', description='销售类型：常规销售/零元购/兑奖/销售换货')
    unit: str = Field(example='箱', description='计量单位：箱/瓶')
    number: float = Field(example=2, gt=0, description='商品数量')
    unitprice: float = Field(example=100.0, ge=0, description='单价（元）')
    remark: Optional[str] = Field(default=None, example='')


class CreateSaleRequest(BaseModel):
    """创建销售订单请求模型"""
    cusid: int = Field(example=1, description='客户ID')
    whid: int = Field(example=1, description='仓库ID')
    owner: int = Field(example=1, default=None, description='业务员ID')
    type: str = Field(example='车销订单', description='订单类型')
    # shtime: date = Field(
    #     default_factory=date.today,
    #     example="2025-09-07",
    #     description='订单时间（默认为当天）'
    # )
    list: List[SaleItemRequest] = Field(
        example=[
            {"pid": 1, "saletype": "常规销售", "unit": "箱", "number": 1, "unitprice": 10},
            {"pid": 2, "saletype": "零元购", "unit": "瓶", "number": 2, "unitprice": 0},
            {"pid": 3, "saletype": "兑奖", "unit": "箱", "number": 3, "unitprice": 30},
            {"pid": 4, "saletype": "销售换货", "unit": "瓶", "number": 4, "unitprice": 40}
        ],
        min_items=1,
        description='至少包含一个商品项'
    )
    remark: Optional[str] = Field(default=None, example='')


@sale_router.post('/create', summary="创建销售订单")
async def create_sale_order(request: CreateSaleRequest, jwt: dict = Depends(my_oauth2_scheme)) -> ApiResponse[dict]:
    """
    创建销售订单接口

    参数:
    - cusid: 客户ID
    - whid: 仓库ID
    - owner: 业务员ID
    - type: 订单类型：车销订单/自提订单
    - list:
        - pid: 商品ID
        - saletype: 销售类型：常规销售/零元购/兑奖/销售换货
        - unit: 单位：箱/瓶
        - number: 商品数量
        - unitprice: 单价（元）
        - number: 商品数量

    """
    try:
        async with in_transaction():
            # 生成销售单号，调用数据库函数 nextvalForMonth
            db = connections.get("default")
            _, result = await db.execute_query("SELECT nextvalForMonth('XS') as next_val")
            if not result or len(result) == 0:
                return ApiResponse.error(500, "生成订单号失败")

            saleid = result[0]["next_val"]
            print("saleid", type(saleid))

            # 获取客户信息
            customer = await Customer.filter(cusid=request.cusid, del_flag__not="2").first()
            if not customer:
                return ApiResponse.error(404, "客户不存在")

            # 获取仓库信息
            warehouse = await Warehouse.filter(whid=request.whid, del_flag__not="2").first()
            if not warehouse:
                return ApiResponse.error(404, "仓库不存在")

            total_amount = 0.0
            order_items = []

            # 处理每个商品项
            for index, item in enumerate(request.list):
                # 获取商品信息
                product = await Product.filter(pid=item.pid, del_flag__not="2").first()
                if not product:
                    return ApiResponse.error(404, f"商品 {item.pid} 不存在")

                # 检查库存
                store_item = await Store.filter(
                    pid=item.pid,
                    whid=request.whid,
                    del_flag__not="2"
                ).first()
                if not store_item:
                    return ApiResponse.error(400, f"商品 {product.pname} 在仓库中无库存")

                # 根据单位类型转换数量
                actual_number = item.number
                if item.unit == product.bigunit and product.formulanum:
                    # 如果是大单位，需要乘以换算系数
                    actual_number = item.number * product.formulanum
                elif item.unit == product.smallunit:
                    # 如果是小单位，直接使用原数量
                    actual_number = item.number
                else:
                    # 如果单位不匹配，返回错误
                    return ApiResponse.error(400,
                                             f"商品 {product.pname} 的单位 '{item.unit}' 与商品定义的单位不匹配（大单位: {product.bigunit}, 小单位: {product.smallunit}）")

                # 检查可用数量是否足够
                if not hasattr(store_item, 'availablenum') or store_item.availablenum is None:
                    return ApiResponse.error(400, f"商品 {product.pname} 可用数量字段不存在或为空")

                # 转换Decimal为float进行比较
                available_num = float(store_item.availablenum)
                if available_num < actual_number:
                    return ApiResponse.error(400, f"商品 {product.pname} 可用数量不足.")
                    # return ApiResponse.error(400, f"商品 {product.pname} 可用数量不足，当前可用数量: {available_num}")

                # 计算金额
                item_amount = item.number * item.unitprice
                total_amount += item_amount

                # 创建销售项
                now = datetime.now()
                sale_item = await SaleItem.create(
                    saleid=str(saleid),
                    orderid=index + 1,
                    pid=item.pid,
                    pname=product.pname,
                    unit=item.unit,
                    saletype=item.saletype,
                    unitprice=item.unitprice,
                    number=item.number,
                    orderamount=item_amount,
                    whid=request.whid,
                    whname=warehouse.whname,
                    remark=item.remark,
                    create_time=now,
                    create_by=jwt["id"],
                    update_time=now
                )
                order_items.append(sale_item)

                # 更新可用数量（需要将float转换为Decimal）
                store_item.availablenum -= Decimal(str(actual_number))
                await store_item.save()

            # 确定owner：如果request.owner为空，则使用当前登录用户ID
            owner_id = request.owner if request.owner else int(jwt["id"])

            # 创建销售订单
            sale_order = await Sale.create(
                saleid=saleid,
                type=request.type,
                cusid=request.cusid,
                cusname=customer.cusname,
                owner=owner_id,
                whid=request.whid,
                orderamount=total_amount,
                whamount=0.00,
                yjamount=0.00,
                wjamount=total_amount,
                statu="待审核",
                shtime=datetime.combine(datetime.now().date(), datetime.min.time()),
                remark=request.remark,
                create_time=now,
                create_by=jwt["id"],
                update_time=now,
                update_by=jwt["id"]
            )

            return ApiResponse.ok(
                data={
                    "saleid": saleid,
                    "total_amount": total_amount,
                    "item_count": len(order_items)
                },
                msg="销售订单创建成功"
            )
    except Exception as e:
        raise ApiResponse.error(500, f"创建车销订单失败: {str(e)}")


# 创建Pydantic模型
SaleItem_Pydantic = pydantic_model_creator(SaleItem, name="SaleItemResponse")
Sale_Pydantic = pydantic_model_creator(Sale, name="SaleResponse")


class SaleResponseWithCreator(Sale_Pydantic):
    """销售订单响应模型（包含创建者昵称）"""
    create_by_name: Optional[str] = None


class SaleDetailResponse(BaseModel):
    """销售订单详情响应模型"""
    sale: SaleResponseWithCreator
    list: List[SaleItem_Pydantic]


@sale_router.get('/detail/{saleid}', summary="查询销售订单详情")
async def get_sale_detail(saleid: str) -> ApiResponse[dict]:
    """
    根据销售单号查询订单详情接口
    """
    try:
        # 查询主订单信息
        sale_order = await Sale.filter(saleid=saleid, del_flag__not="2").first()
        if not sale_order:
            return ApiResponse.error(404, "销售订单不存在")

        # 获取仓库名称
        warehouse_name = None
        if sale_order.whid:
            warehouse = await Warehouse.filter(whid=sale_order.whid, del_flag__not="2").first()
            if warehouse:
                warehouse_name = warehouse.whname

        # 获取经办人名称
        owner_name = None
        if sale_order.owner:
            owner_user = await User.filter(user_id=sale_order.owner, del_flag__not="2").first()
            if owner_user:
                owner_name = owner_user.nick_name

        # 获取创建者名称
        create_by_name = None
        if sale_order.create_by:
            creator = await User.filter(user_id=int(sale_order.create_by), del_flag__not="2").first()
            if creator:
                create_by_name = creator.nick_name

        # 格式化日期字段
        shtime_str = sale_order.shtime.strftime("%Y-%m-%d %H:%M:%S") if sale_order.shtime else None
        create_time_str = sale_order.create_time.strftime("%Y-%m-%d %H:%M:%S") if sale_order.create_time else None
        update_time_str = sale_order.update_time.strftime("%Y-%m-%d %H:%M:%S") if sale_order.update_time else None

        # 查询订单商品项
        sale_items = await SaleItem.filter(
            saleid=saleid,
            del_flag__not="2"
        ).order_by("orderid").all()

        # 构建商品项详情（包含商品信息）
        items_with_product_info = []
        for item in sale_items:
            # 获取商品详细信息
            product_info = None
            if item.pid:
                product = await Product.filter(pid=item.pid, del_flag__not="2").first()
                if product:
                    product_info = {
                        "pcode": product.pcode,
                        "pname": product.pname,
                        "type": product.type,
                        "brand": product.brand,
                        "smallunit": product.smallunit,
                        "smallprice": float(product.smallprice) if product.smallprice else 0.0,
                        "bigunit": product.bigunit,
                        "bigprice": float(product.bigprice) if product.bigprice else 0.0,
                        "status": product.status
                    }

            # 格式化商品项日期字段
            item_create_time_str = item.create_time.strftime("%Y-%m-%d %H:%M:%S") if item.create_time else None
            item_update_time_str = item.update_time.strftime("%Y-%m-%d %H:%M:%S") if item.update_time else None

            items_with_product_info.append({
                "itemid": item.itemid,
                "orderid": item.orderid,
                "pid": item.pid,
                "pname": item.pname,
                "unit": item.unit,
                "saletype": item.saletype,
                "unitprice": float(item.unitprice) if item.unitprice else 0.0,
                "number": float(item.number) if item.number else 0.0,
                "orderamount": float(item.orderamount) if item.orderamount else 0.0,
                "whnumber": float(item.whnumber) if item.whnumber else 0.0,
                "whamount": float(item.whamount) if item.whamount else 0.0,
                "whid": item.whid,
                "whname": item.whname,
                "remark": item.remark,
                "create_time": item_create_time_str,
                "create_by": item.create_by,
                "update_time": item_update_time_str,
                "update_by": item.update_by,
                "product_info": product_info
            })

        # 构建订单详情响应
        detail_response = {
            "sale": {
                "saleid": sale_order.saleid,
                "type": sale_order.type,
                "cusid": sale_order.cusid,
                "cusname": sale_order.cusname,
                "owner": sale_order.owner,
                "ownername": owner_name,
                "whid": sale_order.whid,
                "whname": warehouse_name,
                "orderamount": float(sale_order.orderamount) if sale_order.orderamount else 0.0,
                "whamount": float(sale_order.whamount) if sale_order.whamount else 0.0,
                "yjamount": float(sale_order.yjamount) if sale_order.yjamount else 0.0,
                "wjamount": float(sale_order.wjamount) if sale_order.wjamount else 0.0,
                "statu": sale_order.statu,
                "shtime": shtime_str,
                "remark": sale_order.remark,
                "create_by": sale_order.create_by,
                "create_by_name": create_by_name,
                "create_time": create_time_str,
                "update_by": sale_order.update_by,
                "update_time": update_time_str
            },
            "list": items_with_product_info
        }

        return ApiResponse.ok(data=detail_response, msg="订单详情查询成功")

    except Exception as e:
        return ApiResponse.error(500, f"查询销售订单详情失败: {str(e)}")


@sale_router.get('/list', summary="查询销售订单")
async def get_sales_by_current_user(
        page: int = 1,
        limit: int = 10,
        owner: Optional[int] = Query(None, description="经办人ID"),
        cusid: Optional[int] = Query(None, description="客户ID"),
        start_date: Optional[str] = Query(None, description="开始日期，格式: YYYY-MM-DD"),
        end_date: Optional[str] = Query(None, description="结束日期，格式: YYYY-MM-DD"),
        jwt: dict = Depends(my_oauth2_scheme)
) -> ApiResponse[PageResult[dict]]:
    # 从JWT token中获取当前用户ID
    user_id = jwt["id"]

    # 计算分页偏移量
    offset = (page - 1) * limit

    # 构建查询条件
    query_filters = {"del_flag__not": "2"}

    # 如果指定了owner参数，则按owner过滤，否则按当前用户过滤
    if owner is not None:
        query_filters["owner"] = owner
    else:
        query_filters["owner"] = user_id

    # 如果指定了cusid参数，则添加客户ID过滤
    if cusid is not None:
        query_filters["cusid"] = cusid

    # 处理日期范围过滤
    if start_date:
        try:
            start_dt = datetime.strptime(start_date, "%Y-%m-%d")
            query_filters["create_time__gte"] = start_dt
        except ValueError:
            return ApiResponse.error(400, "开始日期格式错误，请使用YYYY-MM-DD格式")

    if end_date:
        try:
            end_dt = datetime.strptime(end_date, "%Y-%m-%d")
            # 结束日期需要包含当天的23:59:59
            query_filters["create_time__lte"] = datetime.combine(end_dt, datetime.max.time())
        except ValueError:
            return ApiResponse.error(400, "结束日期格式错误，请使用YYYY-MM-DD格式")

    # 查询销售订单
    sales = await Sale.filter(**query_filters).order_by("-create_time").offset(offset).limit(limit)

    # 查询总数量
    total_count = await Sale.filter(**query_filters).count()

    sales_with_details = []
    for sale in sales:
        # 获取经办人名称
        owner_name = None
        if sale.owner:
            owner_user = await User.filter(user_id=sale.owner, del_flag__not="2").first()
            if owner_user:
                owner_name = owner_user.nick_name

        # 获取仓库名称
        warehouse_name = None
        if sale.whid:
            warehouse = await Warehouse.filter(whid=sale.whid, del_flag__not="2").first()
            if warehouse:
                warehouse_name = warehouse.whname

        # 获取创建者名称
        create_by_name = None
        if sale.create_by:
            creator = await User.filter(user_id=int(sale.create_by), del_flag__not="2").first()
            if creator:
                create_by_name = creator.nick_name

        # 格式化日期字段
        shtime_str = sale.shtime.strftime("%Y-%m-%d %H:%M:%S") if sale.shtime else None
        create_time_str = sale.create_time.strftime("%Y-%m-%d %H:%M:%S") if sale.create_time else None
        update_time_str = sale.update_time.strftime("%Y-%m-%d %H:%M:%S") if sale.update_time else None

        sales_with_details.append({
            "saleid": sale.saleid,
            "type": sale.type,
            "cusid": sale.cusid,
            "cusname": sale.cusname,
            "owner": sale.owner,
            "ownername": owner_name,
            "whid": sale.whid,
            "whname": warehouse_name,
            "orderamount": float(sale.orderamount) if sale.orderamount else 0.0,
            "whamount": float(sale.whamount) if sale.whamount else 0.0,
            "yjamount": float(sale.yjamount) if sale.yjamount else 0.0,
            "wjamount": float(sale.wjamount) if sale.wjamount else 0.0,
            "statu": sale.statu,
            "shtime": shtime_str,
            "remark": sale.remark,
            "create_by": sale.create_by,
            "create_by_name": create_by_name,
            "create_time": create_time_str,
            "update_by": sale.update_by,
            "update_time": update_time_str
        })

    # 使用PageResult创建分页结果
    page_result = PageResult.create(rows=sales_with_details, count=total_count)
    return ApiResponse.ok(data=page_result)


@sale_router.get('/list-all', summary="查询所有销售订单（无分页）")
async def get_all_sales(
        owner: Optional[int] = Query(None, description="经办人ID"),
        cusid: Optional[int] = Query(None, description="客户ID"),
        start_date: Optional[str] = Query(None, description="开始日期，格式: YYYY-MM-DD"),
        end_date: Optional[str] = Query(None, description="结束日期，格式: YYYY-MM-DD"),
        jwt: dict = Depends(my_oauth2_scheme)
) -> ApiResponse[List[dict]]:
    """
    查询所有销售订单接口（无分页）
    
    参数:
    - owner: 经办人ID，可选
    - cusid: 客户ID，可选
    - start_date: 开始日期，格式: YYYY-MM-DD，可选
    - end_date: 结束日期，格式: YYYY-MM-DD，可选
    """
    # 从JWT token中获取当前用户ID
    user_id = jwt["id"]

    # 构建查询条件
    query_filters = {"del_flag__not": "2"}

    # 如果指定了owner参数，则按owner过滤，否则按当前用户过滤
    if owner is not None:
        query_filters["owner"] = owner
    else:
        query_filters["owner"] = user_id

    # 如果指定了cusid参数，则添加客户ID过滤
    if cusid is not None:
        query_filters["cusid"] = cusid

    # 处理日期范围过滤
    if start_date:
        try:
            start_dt = datetime.strptime(start_date, "%Y-%m-%d")
            query_filters["create_time__gte"] = start_dt
        except ValueError:
            return ApiResponse.error(400, "开始日期格式错误，请使用YYYY-MM-DD格式")

    if end_date:
        try:
            end_dt = datetime.strptime(end_date, "%Y-%m-%d")
            # 结束日期需要包含当天的23:59:59
            query_filters["create_time__lte"] = datetime.combine(end_dt, datetime.max.time())
        except ValueError:
            return ApiResponse.error(400, "结束日期格式错误，请使用YYYY-MM-DD格式")

    # 查询所有销售订单（无分页）
    sales = await Sale.filter(**query_filters).order_by("-create_time").all()

    sales_with_details = []
    for sale in sales:
        # 获取经办人名称
        owner_name = None
        if sale.owner:
            owner_user = await User.filter(user_id=sale.owner, del_flag__not="2").first()
            if owner_user:
                owner_name = owner_user.nick_name

        # 获取仓库名称
        warehouse_name = None
        if sale.whid:
            warehouse = await Warehouse.filter(whid=sale.whid, del_flag__not="2").first()
            if warehouse:
                warehouse_name = warehouse.whname

        # 获取创建者名称
        create_by_name = None
        if sale.create_by:
            creator = await User.filter(user_id=int(sale.create_by), del_flag__not="2").first()
            if creator:
                create_by_name = creator.nick_name

        # 格式化日期字段
        shtime_str = sale.shtime.strftime("%Y-%m-%d %H:%M:%S") if sale.shtime else None
        create_time_str = sale.create_time.strftime("%Y-%m-%d %H:%M:%S") if sale.create_time else None
        update_time_str = sale.update_time.strftime("%Y-%m-%d %H:%M:%S") if sale.update_time else None

        sales_with_details.append({
            "saleid": sale.saleid,
            "type": sale.type,
            "cusid": sale.cusid,
            "cusname": sale.cusname,
            "owner": sale.owner,
            "ownername": owner_name,
            "whid": sale.whid,
            "whname": warehouse_name,
            "orderamount": float(sale.orderamount) if sale.orderamount else 0.0,
            "whamount": float(sale.whamount) if sale.whamount else 0.0,
            "yjamount": float(sale.yjamount) if sale.yjamount else 0.0,
            "wjamount": float(sale.wjamount) if sale.wjamount else 0.0,
            "statu": sale.statu,
            "shtime": shtime_str,
            "remark": sale.remark,
            "create_by": sale.create_by,
            "create_by_name": create_by_name,
            "create_time": create_time_str,
            "update_by": sale.update_by,
            "update_time": update_time_str
        })

    return ApiResponse.ok(data=sales_with_details, msg="查询成功")


class UpdateSaleItemRequest(BaseModel):
    """更新销售订单商品项请求模型"""
    number: float = Field(example=3, gt=0, description='商品数量')
    unitprice: float = Field(example=120.0, ge=0, description='单价（元）')
    remark: Optional[str] = Field(default=None, example='更新备注')


@sale_router.put('/item/{itemid}', summary="更新销售订单商品项")
async def update_sale_item(
        itemid: int,
        request: UpdateSaleItemRequest,
        jwt: dict = Depends(my_oauth2_scheme)
) -> ApiResponse[dict]:
    """
    更新销售订单商品项接口
    
    参数:
    - itemid: 商品项ID
    - number: 新的商品数量
    - unitprice: 新的单价
    - remark: 新的备注
    """
    try:
        async with in_transaction():
            # 获取商品项信息
            sale_item = await SaleItem.filter(itemid=itemid, del_flag__not="2").first()
            if not sale_item:
                return ApiResponse.error(404, "商品项不存在")

            # 获取销售订单信息
            sale_order = await Sale.filter(saleid=sale_item.saleid, del_flag__not="2").first()
            if not sale_order:
                return ApiResponse.error(404, "销售订单不存在")

            # 检查权限（只有订单创建者或管理员可以修改）
            if sale_order.create_by != str(jwt["id"]):
                return ApiResponse.error(403, "无权修改此订单的商品项")

            # 计算数量差异
            quantity_diff = request.number - sale_item.number

            # 如果需要增加数量，检查库存是否足够
            if quantity_diff > 0:
                store_item = await Store.filter(
                    pid=sale_item.pid,
                    whid=sale_item.whid,
                    del_flag__not="2"
                ).first()

                if not store_item:
                    return ApiResponse.error(400, f"商品ID {sale_item.pid} 在仓库中无库存")

                if not hasattr(store_item, 'availablenum') or store_item.availablenum is None:
                    return ApiResponse.error(400, f"商品ID {sale_item.pid} 可用数量字段不存在或为空")

                # 转换Decimal为float进行比较
                available_num = float(store_item.availablenum)
                if available_num < quantity_diff:
                    return ApiResponse.error(400, f"商品ID {sale_item.pid} 可用数量不足，当前可用数量: {available_num}")

                # 更新可用数量（需要将float转换为Decimal）
                store_item.availablenum -= Decimal(str(quantity_diff))
                await store_item.save()

            # 计算新的金额
            new_amount = request.number * request.unitprice
            old_amount = sale_item.orderamount or 0
            amount_diff = new_amount - old_amount

            # 更新商品项信息
            sale_item.number = request.number
            sale_item.unitprice = request.unitprice
            sale_item.orderamount = new_amount
            sale_item.remark = request.remark
            sale_item.update_time = datetime.now()
            sale_item.update_by = jwt["id"]
            await sale_item.save()

            # 更新订单总金额
            sale_order.orderamount = (sale_order.orderamount or 0) + amount_diff
            sale_order.wjamount = (sale_order.wjamount or 0) + amount_diff
            sale_order.update_time = datetime.now()
            sale_order.update_by = jwt["id"]
            await sale_order.save()

            return ApiResponse.ok(
                data={
                    "itemid": itemid,
                    "new_number": request.number,
                    "new_unitprice": request.unitprice,
                    "new_amount": new_amount,
                    "order_total_amount": sale_order.orderamount
                },
                msg="商品项更新成功"
            )

    except Exception as e:
        return ApiResponse.error(500, f"更新商品项失败: {str(e)}")


@sale_router.delete('/item/{itemid}', summary="删除销售订单商品项")
async def delete_sale_item(
        itemid: int,
        jwt: dict = Depends(my_oauth2_scheme)
) -> ApiResponse[dict]:
    """
    删除销售订单商品项接口
    
    参数:
    - itemid: 商品项ID
    """
    try:
        async with in_transaction():
            # 获取商品项信息
            sale_item = await SaleItem.filter(itemid=itemid, del_flag__not="2").first()
            if not sale_item:
                return ApiResponse.error(404, "商品项不存在")

            # 获取销售订单信息
            sale_order = await Sale.filter(saleid=sale_item.saleid, del_flag__not="2").first()
            if not sale_order:
                return ApiResponse.error(404, "销售订单不存在")

            # 检查权限（只有订单创建者或管理员可以删除）
            if sale_order.create_by != str(jwt["id"]):
                return ApiResponse.error(403, "无权删除此订单的商品项")

            # 恢复库存可用数量
            store_item = await Store.filter(
                pid=sale_item.pid,
                whid=sale_item.whid,
                del_flag__not="2"
            ).first()

            if store_item and hasattr(store_item, 'availablenum') and store_item.availablenum is not None:
                store_item.availablenum += Decimal(str(sale_item.number))
                store_item.update_time = datetime.now()
                store_item.update_by = jwt["id"]
                await store_item.save()

            # 更新订单金额
            item_amount = sale_item.orderamount or 0
            sale_order.orderamount = (sale_order.orderamount or 0) - item_amount
            sale_order.wjamount = (sale_order.wjamount or 0) - item_amount
            sale_order.update_time = datetime.now()
            sale_order.update_by = jwt["id"]
            await sale_order.save()

            # 软删除商品项
            sale_item.del_flag = "2"
            sale_item.update_time = datetime.now()
            sale_item.update_by = jwt["id"]
            await sale_item.save()

            return ApiResponse.ok(
                data={
                    "itemid": itemid,
                    "recovered_quantity": sale_item.number,
                    "order_total_amount": sale_order.orderamount
                },
                msg="商品项删除成功"
            )

    except Exception as e:
        return ApiResponse.error(500, f"删除商品项失败: {str(e)}")


@sale_router.get('/today-stats', summary="今日订单统计")
async def get_today_stats(jwt: dict = Depends(my_oauth2_scheme)) -> ApiResponse[dict]:
    """
    获取今日订单统计信息接口
    
    返回:
    - order_count: 今日订单数
    - order_amount: 今日订单金额
    - received_amount: 今日实收金额
    """
    try:
        # 获取今天的日期（不含时间部分）
        today = datetime.now().date()

        # 从JWT token中获取当前用户ID
        user_id = jwt["id"]

        # 查询今日订单（按当前用户过滤）
        today_sales = await Sale.filter(
            owner=user_id,
            create_time__gte=datetime.combine(today, datetime.min.time()),
            create_time__lt=datetime.combine(today + timedelta(days=1), datetime.min.time()),
            del_flag__not="2"
        ).all()

        # 计算统计信息
        order_count = len(today_sales)
        order_amount = sum(float(sale.orderamount) if sale.orderamount else 0.0 for sale in today_sales)
        received_amount = sum(float(sale.yjamount) if sale.yjamount else 0.0 for sale in today_sales)

        return ApiResponse.ok(
            data={
                "order_count": order_count,
                "order_amount": order_amount,
                "received_amount": received_amount
            }
        )

    except Exception as e:
        return ApiResponse.error(500, f"查询今日统计失败: {str(e)}")
